package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController()
@RequestMapping("/user/user")
@Slf4j
@CrossOrigin
public class UserController {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserService userService;


    @PostMapping("/login")
    @ApiOperation("用户端微信登陆")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO code){
        log.info("用户登录：{}",code);

        User user=userService.login(code);

        //登陆成功后返回jwt

        Map<String, Object> claims=new HashMap<>();

        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO=UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token).build();


        return Result.success(userLoginVO);
    }



    @PostMapping("/logout")
    @ApiOperation("用户端退出登陆")
    public Result<String> logout(){
        log.info("用户退出登录");
        return Result.success();
    }
}
